#include <memory>
#include "tlist.h"

CList::CList( void )
{
	Init();
}

CList::~CList( void )
{
	Init();
}

void CList::Init( void )
{
	m_topObj.priorObj = m_topObj.nextObj = &m_topObj;
}

void CList::AddObj( TListObj* obj )
{
	TListObj* last = m_topObj.priorObj;
	last->nextObj = obj;
	obj->priorObj = last;
	obj->nextObj = &m_topObj;
	m_topObj.priorObj = obj;
}

void CList::DelObj( TListObj* obj )
{
	obj->priorObj->nextObj = obj->nextObj;
	obj->nextObj->priorObj = obj->priorObj;
	obj->nextObj = obj->priorObj = 0;
}

TListObj* CList::TopObj( void )
{
	return &m_topObj == m_topObj.nextObj ? 0 : m_topObj.nextObj;
}

TListObj* CList::NextObj( TListObj* obj )
{
	return &m_topObj == obj->nextObj ? 0 : obj->nextObj;
}

bool CList::IsEmpty( void )
{
	return m_topObj.priorObj == m_topObj.nextObj;
}

void CList::MoveList( CList* fromList )
{
	if( !fromList->IsEmpty() )
	{
		if( IsEmpty() )
		{
			m_topObj = fromList->m_topObj;
			m_topObj.nextObj->priorObj = &m_topObj;
		}
		else
		{
			m_topObj.priorObj->nextObj = fromList->m_topObj.nextObj;
			fromList->m_topObj.nextObj->priorObj = m_topObj.priorObj;
			m_topObj.priorObj = fromList->m_topObj.priorObj;
			fromList->m_topObj.priorObj->nextObj = &m_topObj;
		}
		fromList->Init();
	}
}

CRecycleList::CRecycleList(int init_cnt, int size)
{
	m_data = new char[init_cnt * size];
	memset( m_data, 0, init_cnt * size );

	for (int cnt=0; cnt < init_cnt; cnt++) {
		TListObj *obj = (TListObj *)( m_data + cnt * size);
		m_lists[FREE_LIST].AddObj(obj);
	}
}

CRecycleList::~CRecycleList()
{
	delete[] m_data;
}

TListObj *CRecycleList::GetObj(int list_type)
{
	TListObj	*obj = m_lists[list_type].TopObj();

	if (obj)
		m_lists[list_type].DelObj(obj);

	return	obj;
}

void CRecycleList::PutObj(int list_type, TListObj *obj)
{
	m_lists[list_type].AddObj(obj);
}

